// 退货退款列表

import { useState, useEffect, useMemo } from 'react';
import { Select, Empty, Modal, message } from 'antd';
import { remove } from 'lodash';
import VList from '@/components/VirtualList';
import IconFont from '@/components/IconFont';
import CommonLoading from '@/components/CommonLoading';
import ExportRecordModal from '@/components/ExportRecordModal';
import OperaBtnRender from '@/components/OperaBtnRender';
import GlobalHeader from './GlobalHeader';
import TableHeader from './TableHeader';
import TableSection from './TableSection'
import styles from './index.module.less'
import { getIndexExpressList, applyAgainOp, exprotTableDataOp } from '../../service'

const { Option } = Select;

const ApplyRefundList = ({ data, headerHeight, handleJumptDetail, handleUpdateTable, handleSort, current }) => {

  const [expressList, setExpressList] = useState([]);
  const [selectRowKeys, setSelectRowKeys] = useState([]);//选中数据（订单id)
  const [selectRows, setSelectRows] = useState([]);//选中数据
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    getExpressList();
  }, [])

  //获取快递列表
  const getExpressList = async () => {
    const { success, data } = await getIndexExpressList();
    if (success) {
      setExpressList(data);
    }
  }

  //点击选择行
  const handleSelect = (e, data) => {
    const val = e.target.checked;
    let arr = [];
    if (val) {
      arr = [...selectRowKeys, data.id];
      selectRows.push(data);
    } else {
      arr = selectRowKeys.filter(v => v != data.id);
      remove(selectRows, function (n) {
        return n.id == data.id;
      })
    }
    setSelectRowKeys(arr);
    setSelectRows([...selectRows]);
  }

  //渲染行信息
  const rowRender = ({ index, style }) => {
    const obj = data[index];
    const isSelect = selectRowKeys.includes(obj.id);
    return (
      <div className={styles.row} key={index} style={style}>
        <div className={styles.wrap} >
          <TableHeader data={obj} isSelect={isSelect} handleSelect={handleSelect} /> {/* 顶部渲染信息 */}
          <TableSection data={obj} expressList={expressList} handleJumptDetail={handleJumptDetail} handleUpdateTable={handleUpdateTable} /> {/* 内容区渲染信息 */}
        </div>
      </div>
    );
  }

  //表头
  const GlobalHeaderProps = {
    checked: (selectRowKeys.length > 0 && selectRowKeys.length == data.length) ? true : false,
    isDisabled: data.length == 0 ? true : false,
    indeterminate: (selectRowKeys.length > 0 && selectRowKeys.length < data.length) ? true : false,
    handleClick(e) {
      let val = e.target.checked;
      if (val) {
        const arr = data.map(v => v.id);
        setSelectRowKeys(arr);
        setSelectRows([...data]);
      } else {
        setSelectRowKeys([]);
        setSelectRows([]);
      }
    },
  }

  const getRowHeight = (index) => {
    const arr = data[index].refundOrderGoodsList || [],
      length = arr.length;
    if (length) {
      const { channelId, afterSalesType, refundState } = data[index];
      return 52 + 142 * length + ((channelId === 0) && (afterSalesType == 1 || afterSalesType == 2 || refundState == 4) ? 35 : 0)
    } else {
      return 178
    }
  }

  //获取滚动高度
  const listHeight = useMemo(() => {
    const el = document.body;
    if(el) {
      const height = el.clientHeight - headerHeight - 312;
      return height;
    }
    return 300;
  }, [headerHeight])

  //虚拟list
  const VListProps = {
    rowRender,
    listHeight,
    rowCount: data.length,
    useDyRowHeight: true,
    getRowHeight: getRowHeight,
    style: { minWidth: '1200px', overflowX: 'auto', width: '100%' }
  }

  //重新申请操作
  const zhifaApplyAgainOperator = async () => {
    setLoading(true);
    const { success } = await applyAgainOp({ refundOrderIds: selectRowKeys, isBatch: 1 });
    if (success) {
      message.success('重新申请成功！');
      handleUpdateTable();
    }
    setLoading(false);
  }

  const handleApplyAgain = () => {
    if (selectRows.length) {
      const notValid = selectRows.some(item => item.refundState != 1);
      if (notValid) {
        Modal.info({
          title: '温馨提示',
          content: '批量重新申请，只能处理”商家已拒绝“类型的售后单，请重新勾选！',
        })
      } else {
        Modal.confirm({
          title: '重新申请',
          content: (<>
            <p>是否确认重新申请？</p>
            <span>注意：如果是“退货退款”的重新申请，批量操作会按照原申请数据重新提交</span>
          </>),
          onOk() {
            zhifaApplyAgainOperator();
          }
        })
      }
    } else {
      Modal.info({ content: '请先勾选售后单' });
    }
  }


  //导出api
  const handleExport = async () => {
    if (current.total) {
      setLoading(true);
      const { success } = await exprotTableDataOp(current);
      setLoading(false);
      if (success) {
        Modal.confirm({
          icon: <IconFont type="iconchenggong" />,
          title: <span className="common-color10">成功提示</span>,
          content: (
            <div>
              您的文件正在导出中 <br />
              可以去“任务中心”查看导出进度和结果！
            </div>
          ),
          okText: '去查看',
          cancelText: '关闭',
          onOk() {
            setVisible('exportVisible');
          },
        });
      }
    } else {
      message.info('暂无数据导出，请重新查询')
    }
  };

  //当前账号当天表格导出记录  modalprops
  const exportRecordProps = {
    visible: visible == 'exportVisible',
    handleCancel() {
      setVisible(false);
    }
  }

  //操作按钮
  const btnArr = [
    { elType: 'button', text: '重新申请', onClick: handleApplyAgain },
    { elType: 'button', text: '表格导出', onClick: handleExport },
  ]

  return (<>
    <div style={{ display: "flex", justifyContent: 'space-between', marginBottom: "12px" }}>
      <OperaBtnRender style={{ marginBottom: '12px' }} btnArr={btnArr} />
      <span>
        <Select style={{ width: "120px" }} defaultValue={1} onChange={handleSort}>
          <Option key={1} value={1}>最新申请排序</Option>
          <Option key={2} value={2}>临近超时排序</Option>
        </Select>
      </span>
    </div>
    <GlobalHeader {...GlobalHeaderProps} />
    {
      data.length ?
        <VList {...VListProps} />
        : <Empty style={{ background: '#fff', padding: '24px' }} description='暂无数据' />
    }
    {visible == 'exportVisible' && <ExportRecordModal {...exportRecordProps} />}
    <CommonLoading loading={loading} />
  </>
  )
}

export default ApplyRefundList
